package com.gccloud.design;

import com.gccloud.design.dto.ActivityElementDto;
import com.gccloud.design.dto.OptButtonBranchRelDto;
import com.gccloud.design.entity.OptButtonBranchRelEntity;
import com.gccloud.design.entity.SdActionConfEntity;
import com.gccloud.design.feign.BwpOperDockingClient;
import com.gccloud.design.service.ButtonConfigService;
import com.gccloud.design.service.SdActionConfQueryService;
import com.gccloud.design.utils.ConstantUtil;
import com.gccloud.feign.filter.dto.SysUser;
import com.gccloud.idc.security.shiro.UserUtils;
import com.gccloud.starter.common.dto.SearchDTO;
import com.gccloud.starter.common.exception.GlobalException;
import com.gccloud.starter.common.utils.BeanConvertUtils;
import com.gccloud.starter.common.vo.R;
import com.gccloud.starter.core.vo.PageVO;
import com.ustcinfo.bwp.client.support.BwpServiceFactory;
import com.ustcinfo.bwp.modle.ProcessDefine;
import com.ustcinfo.bwp.modle.elements.ActivityElement;
import com.ustcinfo.bwp.service.FlowService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 按钮配置
 *
 * @author li.tao2
 */
@RestController
@RequestMapping("/buttonConfig")
@Api(tags = "操作按钮配置API")
@ApiSort(value = 12)
public class ButtonConfigController {

    @Resource
    private SdActionConfQueryService sdActionConfQueryService;
    @Resource
    private BwpOperDockingClient bwpOperDockingClient;
    @Resource
    private ButtonConfigService buttonConfigService;

    FlowService flowService = BwpServiceFactory.getFlowService();

    private static final Logger log = LoggerFactory.getLogger(ButtonConfigController.class);

    /**
     * 获取流程
     *
     * @return R<List < ProcessDefine>>
     */
    @GetMapping("/getProcess")
    @ApiOperation(value = "获取流程", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<List<ProcessDefine>> getProcess() {
        List<ProcessDefine> idc = flowService.getAllProcessInfoBySysCode(ConstantUtil.ProcessInfoBySysCode);
        return R.success(idc);
    }

    /**
     * 获取流程环节
     *
     * @param processDefine 流程定义
     * @param pageObj       分页对象
     * @return R<Map < String, Object>>
     */
    @GetMapping("/getProcessLink")
    @ApiOperation(value = "获取流程环节", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "页码", paramType = "query", required = true, dataType = "long"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", required = true, dataType = "long"),
            @ApiImplicitParam(name = "processDefine", value = "流程定义", paramType = "query", dataType = "string")
    })
    public R<Map<String, Object>> getProcessLink(String processDefine, PageVO pageObj) {
        Map<String, Object> map = new HashMap<>(4);
        List<ActivityElementDto> activityElementList = new LinkedList<>();
        FlowService flowService = BwpServiceFactory.getFlowService();
        //获取流程环节信息
        Map<String, ActivityElement> processInfo = flowService.getActElementsByProcessDefName(processDefine);
        for (String key : processInfo.keySet()) {
            ActivityElementDto dto = new ActivityElementDto();
            if ("开始".equals(processInfo.get(key).getName()) || "结束".equals(processInfo.get(key).getName())) {
                continue;
            }
            dto.setRepoId(processInfo.get(key).getRepoId());
            dto.setName(processInfo.get(key).getName());
            dto.setType(processInfo.get(key).getType());
            activityElementList.add(dto);
        }
        int startDataNum = (int) ((pageObj.getCurrent() - 1) * pageObj.getSize());
        int endDataNum = (int) (pageObj.getCurrent() * pageObj.getSize());
        int activityEleTotal = activityElementList.size();
        if (endDataNum < activityEleTotal) {
            map.put("datas", activityElementList.subList(startDataNum, endDataNum));
        } else {
            map.put("datas", activityElementList.subList(startDataNum, activityEleTotal));
        }
        map.put("total", activityElementList.size());
        return R.success(map);
    }

    /**
     * 查询操作按钮
     *
     * @param actionName 环节操作按钮名称
     * @param pageObj    分页对象
     * @return R
     */
    @ApiOperation(value = "查询操作按钮", produces = MediaType.APPLICATION_JSON_VALUE)
    @GetMapping("/querySdActionConf")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "页码", paramType = "query", required = true, dataType = "long"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", required = true, dataType = "long"),
            @ApiImplicitParam(name = "actionName", value = "操作按钮名称", paramType = "query", dataType = "string")
    })
    public R querySdActionConf(String actionName, PageVO pageObj) {
        SearchDTO dto = new SearchDTO();
        dto.setSearchKey(actionName);
        dto.setCurrent((int) pageObj.getCurrent());
        dto.setSize((int) pageObj.getSize());
        return bwpOperDockingClient.queryButtonList((int) pageObj.getCurrent(), (int) pageObj.getSize(), actionName);
    }

    /**
     * 新增操作按钮
     *
     * @param entity 操作按钮实体
     * @return R<Object>
     */
    @PostMapping(value = "/saveSdActionConf")
    @ApiOperation(value = "新增操作按钮")
    public R<Object> saveSdActionConf(@RequestBody SdActionConfEntity entity) {
        SysUser currentUser = UserUtils.getCurrentUser();
        String userId = currentUser.getName();
        entity.setCreateUserId(userId);
        entity.setLastModUserId(userId);
        boolean result = sdActionConfQueryService.saveSdActionConf(entity);
        return R.success(result);
    }

    /**
     * 更新操作按钮
     *
     * @param entity 环节操作按钮实体
     * @return R<Object>
     */
    @PostMapping(value = "/modefySdActionConf")
    @ApiOperation(value = "更新操作按钮")
    public R<Object> modefySdActionConf(@RequestBody SdActionConfEntity entity) {
        SysUser currentUser = UserUtils.getCurrentUser();
        String userId = currentUser.getName();
        entity.setLastModUserId(userId);
        boolean result = sdActionConfQueryService.modefySdActionConf(entity);
        return R.success(result);
    }

    /**
     * 删除按钮配置
     *
     * @param actionId 环节按钮标识
     * @return R<Object>
     */
    @ApiOperation(value = "删除按钮配置", notes = "根据按钮Id删除按钮")
    @GetMapping("/deletdSdActionConf")
    @ApiImplicitParam(name = "actionId", value = "按钮Id", required = true, dataType = "int", paramType = "path")
    public R<Object> deletdSdActionConf(Integer actionId) {
        if (actionId == null || actionId <= 0) {
            throw new GlobalException("请求入参有误");
        }
        sdActionConfQueryService.deleteSdActionConf(actionId);
        return R.success(actionId);
    }

    /**
     * 查询操作按钮分支
     *
     * @param buttonId 环节按钮标识
     * @param pageObj  分页对象
     * @return Map
     */
    @ApiOperation(value = "查询操作按钮分支", produces = MediaType.APPLICATION_JSON_VALUE)
    @GetMapping("/newQueryButtonBranch")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "页码", paramType = "query", required = true, dataType = "long"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", required = true, dataType = "long"),
            @ApiImplicitParam(name = "buttonId", value = "查询条件", paramType = "query", dataType = "string")
    })
    public R<Map<String, Object>> newQueryButtonBranch(Integer buttonId, PageVO pageObj) {
        if (buttonId == null || buttonId <= 0) {
            throw new GlobalException("请求入参有误");
        }
        Map<String, Object> dataMap = buttonConfigService.newQueryButtonBranch(buttonId, pageObj);
        return R.success(dataMap);
    }

    /**
     * 新增操作按钮分支关系
     *
     * @param optButtonBranchRelDto 按钮分支关系实体
     * @return R<Object>
     */
    @PostMapping(value = "/newAddButtonBranchRel")
    @ApiOperation(value = "")
    public R<Object> newAddButtonBranch(@RequestBody OptButtonBranchRelDto optButtonBranchRelDto) {
        OptButtonBranchRelEntity entity = BeanConvertUtils.convert(optButtonBranchRelDto, OptButtonBranchRelEntity.class);
        boolean result = buttonConfigService.newAddButtonBranch(entity);
        return R.success(result);
    }

    /**
     * 删除按钮分支关系配置
     *
     * @param buttonId    按钮标识
     * @param optBranchId 操作分支标识
     * @return R<Object>
     */
    @GetMapping("/newDeleteButtonBranchRel")
    @ApiOperation(value = "删除按钮分支关系配置", notes = "根据按钮Id，分支id删除按钮")
    public R<Object> newDeleteButtonBranchRel(int buttonId, int optBranchId) {
        boolean result = buttonConfigService.newDeleteButtonBranchRel(buttonId, optBranchId);
        return R.success(result);
    }

    /**
     * 查询操作按钮分支
     *
     * @param buttonId       按钮ID
     * @param businessTypeId 业务类型标识
     * @return Map
     */
    @GetMapping("/queryOptButtonBranch")
    @ApiOperation(value = "查询操作按钮分支", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "buttonId", value = "按钮ID", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "businessTypeId", value = "业务类型ID", paramType = "query", required = true, dataType = "String"),
    })
    public R<Map<String, Object>> newQueryButtonBranch(Integer buttonId, String businessTypeId) {
        return R.success(buttonConfigService.queryOptButtonBranch(buttonId, businessTypeId));
    }

    /**
     * 查询流程业务类型
     *
     * @return Map
     */
    @GetMapping("/queryBusinessType")
    @ApiOperation(value = "查询流程业务类型", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Map<String, Object>> queryBusinessType() {
        Map<String, Object> dataMap = buttonConfigService.queryBusinessType();
        return R.success(dataMap);
    }
}
